<template>
<div class="Login_con">
<!--  登入-->
  <div class="Login_box">
<!--    登入头像-->
    <div class="avater">
      <img src="../assets/logo.png">
    </div>

    <el-form ref="loginFormRef" :rules="loginFormrules" :model="loginForm" label-width="0px" class="login_Form" >
      <!--  用户名  -->
      <el-form-item prop="username">
        <el-input v-model="loginForm.username"  prefix-icon="el-icon-search" ></el-input>
      </el-form-item>
      <!--  密码  -->
      <el-form-item prop="password">
        <el-input type="password" v-model="loginForm.password" prefix-icon="el-icon-search"></el-input>
      </el-form-item>
      <!--  按钮  -->
      <el-form-item class="btns">
        <el-button type="primary" @click="login">登入</el-button>
        <el-button type="info" @click="restLoginForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</div>
</template>

<script>
export default {
  data () {
    // 表单数据绑定
    return {
      loginForm: {
        username: '',
        password: ''
      },
      // 表单规则验证
      loginFormrules: {
        username: [
          // 用户名验证
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 7, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          // 密码验证
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 7, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    restLoginForm () {
      this.$refs.loginFormRef.resetFields()
    },
    login () { // 表单预验证
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return 0
        const { data: res } = await this.$http.post('login', this.loginForm) // 调用请求接口
        // console.log(result)
        if (res.meta.status !== 200) { return this.$message.error('登入失败') } // 根据后台返回的状态码判断登入状态
        this.$message.success('登入成功')
        // 1.将登入成功之后的token保存到客户端的sessionStorage中
        //  1.1项目中除了登入之外的其他API接口，必须在登入之后才能访问
        //  1.2token只应在当前网站打开期间生效，所以将 token 保存在 sessionStorage中
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.Login_con{
  background-color: cadetblue;
  height: 100%;
}
.Login_box{
  background-color: #fff;
  width: 450px;
  height: 300px;
  border-radius: 3px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
.avater{
  height: 130px;
  width: 130px;
  border:1px solid #eee;
  border-radius: 50%;
  padding: 10px;
  box-shadow: 0 0 10px #ddd;
  position: absolute;
  left: 50%;
  transform: translate(-50%,-50%);
  background-color: #fff;
  img{
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: #eee;
  }
}
.btns{
  display: flex;
  justify-content: flex-end;
}
.login_Form{
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}
</style>
